package com.xinzhitong.www.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xinzhitong.www.exception.ConsignGeneralException;
import com.xinzhitong.www.exception.SystemException;
import com.xinzhitong.www.exception.consigngeneralexception.NoConsignGeneralException;
import com.xinzhitong.www.exception.system.NullContactUsFileException;
import com.xinzhitong.www.exception.system.NullServiceAgreementException;
import com.xinzhitong.www.exception.system.OpinionTextIsNullException;
import com.xinzhitong.www.mapper.SystemMapper;
import com.xinzhitong.www.pojo.ContactUs;
import com.xinzhitong.www.pojo.Opinion;
import com.xinzhitong.www.pojo.User;
import com.xinzhitong.www.service.SystemService;
import com.xinzhitong.www.utils.*;
import org.apache.ibatis.javassist.expr.NewArray;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统服务实现
 *
 * @author 魏骆淳 吴展鹏
 */
@Service
@Transactional
public class SystemServiceImpl implements SystemService {

    @Resource
    private SystemMapper systemMapper;

    @Override
    public void putOpinionInformation(String opinionText, List<MultipartFile> opinionPicture) throws SystemException {

        if (opinionText == null) {
            throw new OpinionTextIsNullException();
        } else {
            Subject subject = SecurityUtils.getSubject();
            User user = (User) subject.getPrincipal();
            systemMapper.insertOpinionText(user.getUsername(), opinionText);
            Opinion opinion = systemMapper.selectOpinionDatetime();

            if (opinionPicture.size() != 0) {
                //存入意见图片
                for (int i = 0; i < opinionPicture.size(); i++) {
                    String path =
                            "/static/opinion/" +
                                    user.getUsername() + "/" + opinion.getDatetime() + "/" + (i + 1) + ".jpg";
                    path = UrlNormalize.urlNormalize(path);
                    try {
                        FileHelper.saveTo(path, opinionPicture.get(i));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    systemMapper.insertOpinionPicture(opinion.getId(), path);
                }
            }
        }
    }

    @Override
    public List<String> putNewOpinionInformation(String opinionText,Integer opinionPictureNum) throws SystemException{

        if (opinionText == null){
            throw new OpinionTextIsNullException();
        }else{
            Subject subject = SecurityUtils.getSubject();
            User user = (User)subject.getPrincipal();
            systemMapper.insertOpinionText(user.getUsername(),opinionText);
            Opinion opinion = systemMapper.selectOpinionDatetime();
            List<String> pictureAddress = new ArrayList<>();
            if(opinionPictureNum != 0){
                //存入意见图片
                for(int i=0;i<opinionPictureNum;i++){
                    String path =
                            "/static/opinion/"
                                    +user.getUsername()+ "/" +opinion.getDatetime()+"/"+(i+1)+".jpg";
                    path = UrlNormalize.urlNormalize(path);
                    pictureAddress.add(path);
                    systemMapper.insertOpinionPicture(opinion.getId(),path);
                }
            }
            return pictureAddress;
        }
    }

    @Override
    public Map<String, Object> getAboutUs() throws NullContactUsFileException {

        List<String> aboutUs = getFile("static/aboutUs.txt");
        if (aboutUs == null) {
            throw new NullContactUsFileException();
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("aboutUs", aboutUs);
            return (map);
        }
    }

    @Override
    public Map<String, Object> getContactUs() throws NullContactUsFileException {

        ContactUs contactUs = new ContactUs();
        PropertiesHelper.getFromPropertiesFile("contactUs.properties", contactUs);
        Map<String, Object> map = new HashMap<>();
        map.put("phone", contactUs.getPhone());
        map.put("email", contactUs.getEmail());
        map.put("location", contactUs.getLocation());
        return (map);
    }

    @Override
    public Map<String, Object> getServiceAgreement() throws NullContactUsFileException {

        String serviceAgreement = FileHelper.getOssFile(FileHelper.fileURL+"/static/serviceAgreement.txt");
        String[] a = serviceAgreement.split("\n");

        if (serviceAgreement == null) {
            throw new NullServiceAgreementException();
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("serviceAgreement", a);
            return (map);
        }
    }

    @Override
    public Map<String, Object> getOpinionInformation(Integer id) {
        Map<String, Object> x = systemMapper.selectOpinionText(id);
        List<String> y = systemMapper.selectOpinionPicture(id);
        if (y == null) {
            x.put("picture", null);
        } else {
//            for (String temp:y){
//                temp=FileHelper.fileURL+temp;
//
//
//                            }
            for (int i = 0; i < y.size(); i++) {
                y.set(i, FileHelper.fileURL + y.get(i));
            }
            x.put("picture", y);
        }

        if (x.get("datetime") == null)
            x.put("datetime", null);
        else
            x.replace("datetime", x.get("datetime").toString());

        return x;
    }

    /**
     * 获取文本文件内容
     *
     * @param path 文本文件路径
     * @return 文本内容
     */
    private List<String> getFile(String path) {
        ClassPathResource classPathResource = new ClassPathResource(path);
        InputStream inputStream = null;
        try {
            inputStream = classPathResource.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        assert inputStream != null;
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        List<String> content = new ArrayList<>();
        for (; ; ) {
            try {
                String line = br.readLine();
                if (line == null) {
                    break;
                } else {
                    content.add(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content;
    }

    @Override
    public String deleteOpinion(List<Integer> idList) {
        String a;
        for (Integer id : idList) {
            systemMapper.deleteOpinion(id);
        }
        a = "反馈删除成功";
        return a;
    }

    @Override
    public MyPageInfo getOpinionGeneral(String state, String name, Integer pageNo, Integer pageSize)
            throws ConsignGeneralException {
        PageHelper.startPage(pageNo, pageSize);
        String name1 = SearchKeyUtil.makeKey(name);
        String state1 = SearchKeyUtil.makeKey(state);

        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        List<Map<String, Object>> x = systemMapper.selectOpinionGeneral(name1, state1);
        if (x.size() == 0)
            throw new NoConsignGeneralException();

        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(x);
        for (Map<String, Object> temp : pageInfo.getList()) {
            if (temp.get("text").toString().length() > 10) {
                temp.replace("text", temp.get("text").toString().substring(0, 9));

            }
        }
        for (Map<String, Object> temp : pageInfo.getList()) {
            if (temp.get("datetime") == null)
                temp.put("datetime", null);
            else
                temp.replace("datetime", temp.get("datetime").toString());
        }
        return new MyPageInfo(pageInfo);
    }

}
